import React, { Component } from 'react';
import { Tab, Table, Pagination, Loading, Animate, Message } from '@alifd/next';
import {
  refreshAble,
  TransferTable,
  TransferHoc,
  BatchWrapper,
} from '@src/components/index';
import {
  requestLoanList,
  requestDelProject,
  requestWorkFlowStart,
} from './reducer/MyProjectAction';
import {
  BasicDetail
} from './components/index';
import FoundationSymbol from '@icedesign/foundation-symbol';
import { withRouter } from 'react-router';
import ScrollbarStyle from '@src/common/ScrollbarStyle';

import './MyProject.scss'

const tabs = [
  { tab: '我的项目', key: 0, },
];

@withRouter
@refreshAble('myProject')
class MyProject extends Component {
  static displayName = 'MyProject';

  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      dataSource: [],
      isShow: false,
      loading: false,
      height: `${document.documentElement.clientHeight - 260}px`,
      itemApplyId: '',
      isShowBatch: false,
    };
  }

  componentDidMount() {
    this.onRefresh();

    window.addEventListener('resize', this.handleHeight);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleHeight);

    this.props.fetchDataCancle();

    ScrollbarStyle.removeListener();
  }

  onRefresh = () => {
    this.props.fetchData(requestLoanList(1));
  }

  handleHeight = () => {
    const screenHeight = document.documentElement.clientHeight;
    let height = `${screenHeight - 260}px`;
    if (screenHeight < 472) {
      height = 'auto'
    }

    this.setState({
      height
    })
  }

  handleSort = (dataIndex, order) => {
    const dataSource = this.state.dataSource.sort((a, b) => {
      const result = a[dataIndex] - b[dataIndex];
      if (order === 'asc') {
        return result > 0 ? 1 : -1;
      }
      return result > 0 ? -1 : 1;
    });

    this.setState({
      dataSource,
    });
  };

  setCellProps = (rowIndex, colIndex, dataIndex, record) => {
    //console.log('my record==',record)
    const { itemApplyId } = record;
    let that = this;
    if (colIndex === 1) {
      let propsConf = {
        style: { color: '#3ea8f5', cursor: 'pointer' },
        onClick: (event) => {
          event.stopPropagation();
          that.setState({
            isShow: true,
            itemApplyId: itemApplyId
          })
        },
      }
      return propsConf;
    }
  }

  hideShow = (event, obj) => {
    if (this.state.isShow) {
      this.setState({
        isShow: false
      })
    }
  }

  setRowProps = (record, index) => {
    return {
      style: { height: '60px', fontSize: '14px' }
    }
  }

  handlePagination = (current) => {
    this.setState({
      current: current
    })
    this.props.fetchData(requestLoanList(current));
  };

  renderTableColumn = (headerDatas) => {
    if (headerDatas && headerDatas.length > 0) {
      return headerDatas.map((item, index) => {
        return (
          <Table.Column
            title={item.headerName}
            dataIndex={item.headerKey}
            key={index}
            cell={item.cell || ((value) => value)}
            width={220 || 'auto'}
            height={50}
          //lock={ index === 0 ? 'left' : false}
          />
        )
      })
    }
  }

  rowOnSelect = (selected, record, records) => {
    console.log(record)
    const { itemApplyId } = record;
    this.setState({
      isShowBatch: true,
      itemApplyId: itemApplyId,
    })
  }

  delItemApplyById = async (itemApplyId) => {
    let model;
    try {
      model = await requestDelProject(itemApplyId);
      if (model) {
        Message.show({
          type: 'success',
          title: '删除成功',
        });
        this.setState({
          isShowBatch: false
        })
        this.onRefresh();
      }
    } catch (error) {
      console.log(error);
    }
  }

  hideBatchWrapper = (event) => {
    event.stopPropagation();
    this.setState({
      isShowBatch: false
    })
  }

  onInitiationProcess = async (itemApplyId) => {
    let model;
    try {
      let data = {
        key: "test1",
        businessKey: itemApplyId,
        user: "10000028061339"
      }
      model = await requestWorkFlowStart(data);
      if (model) {
        Message.show({
          type: 'success',
          title: '发布成功',
        });
        this.setState({
          isShowBatch: false
        })
        //this.onRefresh();
      }
    } catch (error) {
      console.log(error);
    }
  }

  renderBtnItem = () => {
    const { itemApplyId } = this.state;
    return (
      <div className="batch-btns">
        <div className="btn-item" onClick={() => { this.delItemApplyById(itemApplyId) }}>
          <FoundationSymbol size="small" type={'delete'} />
          <span>删除</span>
        </div>
        <div className="btn-item" onClick={() => { this.onInitiationProcess(itemApplyId) }}>
          <FoundationSymbol size="small" type={'repair'} />
          <span>发起流程</span>
        </div>
      </div>
    )
  }

  render() {

    const {
      isShow,
      loading,
      isShowBatch,
      itemApplyId,
    } = this.state;

    const {
      history,
      data,
      isRefreshing,

      showTransfer,
      dataSource,
      defaultValue,
      filterTableHeaders,

      handleTransfer,
      handleChange,
      saveTransferSet,
      restoreDefault,

    } = this.props;

    let tableDataValues, tableHeaders, totalCount;
    if (data && data.data) {
      tableDataValues = data.data.tableDataValues;
      tableHeaders = data.data.tableHeaders;
      totalCount = data.data.totalCount;

      setTimeout(() => {
        ScrollbarStyle.tableBody = document.querySelector('.scrollbar-table .next-table-body');
        ScrollbarStyle.tableHeader = document.querySelector('.scrollbar-table .next-table-header');
        if (ScrollbarStyle.tableBody != null) {
          ScrollbarStyle.initScroll();
        }
      })
    }

    let setUp = (
      <div className="bar-tabs-wrapper">
        <div className="tab-button-wrapper" onClick={() => {
          history.push('/table/project_create');
        }}>
          <FoundationSymbol size="small" type={'shezhi'} />
          <span className="btn-text">新增项目</span>
        </div>
        <div className="tab-button-wrapper" onClick={() => { handleTransfer(tableHeaders) }}>
          <FoundationSymbol size="small" type={'shezhi'} />
          <span className="btn-text">编辑字段</span>
        </div>
      </div>
    )

    return (
      <div className="layout-content-box">
        {
          isShow ? (
            <BasicDetail itemApplyId={itemApplyId} hideShow={this.hideShow} />
          ) : ""
        }

        {
          showTransfer ? (
            <TransferTable
              handleChange={handleChange}
              restoreDefault={restoreDefault}
              saveTransferSet={saveTransferSet}
              handleTransfer={handleTransfer}
              defaultValue={defaultValue}
              dataSource={dataSource}
            />
          ) : ""
        }

        <Animate animation={{
          enter: 'expandInDown',
          leave: 'expandOutUp'
        }}>
          {
            isShowBatch ? (<BatchWrapper
              hideBatchWrapper={this.hideBatchWrapper}
              renderBtnItem={this.renderBtnItem()}
            />) : null
          }
        </Animate>
        <Tab extra={setUp}>
          <Tab.Item title={tabs[0].tab} key={tabs[0].key}>
            <Table
              style={{ borderBottom: '1px solid #DCDEE3' }}
              dataSource={tableDataValues ? tableDataValues : []}
              onSort={this.handleSort}
              hasBorder={false}
              className="scrollbar-table"
              primaryKey={"itemApplyId"}   //启用可选后指定的Key
              rowSelection={{
                mode: 'single',
                onSelect: this.rowOnSelect
              }}  //启用可选
              getCellProps={this.setCellProps}
              getRowProps={this.setRowProps}
              fixedHeader={true}
              maxBodyHeight={this.state.height}
              loading={isRefreshing || loading}
            >
              {this.renderTableColumn(filterTableHeaders && filterTableHeaders.length > 0 ? filterTableHeaders : tableHeaders)}
            </Table>
            <Pagination
              pageSize={10}
              className="pagination"
              current={this.state.current}
              onChange={this.handlePagination}
              total={parseInt(totalCount)}
              totalRender={total => `Total: ${parseInt(totalCount)}`}
            />
          </Tab.Item>
        </Tab>
      </div>
    );
  }
}

export default TransferHoc(MyProject);